##=============================================================================
## Appendix Figure 3
##=============================================================================

##-----------------
# clear environment
rm(list=ls())
options(stringsAsFactors = FALSE, scipen = 999)
# source("R/functions.R")

seed <- sample.int(.Machine$integer.max, 1)
set.seed(seed)

ipak <- function(pkg){new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
if(length(new.pkg)) install.packages(new.pkg, dependencies = TRUE)
sapply(pkg, require, character.only = TRUE)
}

packages <- c("tidyverse", "hrbrthemes")

ipak(packages)

##---------
# Load data
#setwd("/Users/austinknuppe/Library/CloudStorage/Dropbox/Ukraine2022WartimeSurvey/Paper_peace/final_version_oct_2024/replication-scripts")
load("clean_ukraine_data.RData")

##---------
# Returnees
dtm <- dtm %>% 
  filter(type == "returnee") 

flows <- expand_grid(date = dtm$date, adm1_en = dtm$adm1_en) %>%
  distinct() %>% 
  arrange(date, adm1_en)

dtm <- dtm %>% 
  select(adm1_en, date, flows) %>% 
  group_by(adm1_en, date) %>% 
  summarize(nom_flows = sum(flows))

flows <- left_join(flows, dtm, by = c("date", "adm1_en")) %>% 
  mutate(nom_flows = ifelse(is.na(nom_flows), 0, nom_flows))

flows <- flows %>% 
  filter(nom_flows != 0) %>% 
  filter(adm1_en == "Kyiv" | adm1_en == "Kyivska" | adm1_en == "Chernihivska" |
           adm1_en == "Kharkivska" | adm1_en == "Lvivska" | adm1_en == "Odeska")

ggplot(flows, aes(x = date, y = nom_flows)) +
  facet_wrap(~adm1_en, nrow = 3) +
  geom_area(fill = "gray75", color = "gray10") +
  labs(title = NULL, x = NULL, y = "Returnees (count)") +
  theme_ipsum(axis_title_size = 24, 
              axis_text_size = 18)

rm(list = ls())
##=============================================================================
## End of File
##=============================================================================